<script lang="ts" setup>
import {
  ElButton,
  ElInput,
  ElTable,
  ElSwitch,
  ElPagination,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElRow,
  ElCol,
  ElMessage,
} from "element-plus";
import { ref, onMounted } from "vue";
import { router } from "#/router";
import { getTaskList, editTaskStatus } from "#/api/sys/task";
import { useDebounceFn } from "@vueuse/core";

const taskName = ref("");
const taskType = ref("");
const status = ref("");

const tableData = ref([]);
const taskOptions = [
  {
    value: "1",
    label: "巡检任务",
  },
  {
    value: "2",
    label: "警情任务",
  },
  {
    value: "3",
    label: "一键起飞",
  },
];
const statusOptions = [
  {
    value: "1",
    label: "待执行",
  },
  {
    value: "2",
    label: "执行中",
  },
  {
    value: "3",
    label: "已终止",
  },
  {
    value: "4",
    label: "已取消",
  },
  {
    value: "5",
    label: "已完成",
  },
];
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);

const spaceInput = (field: keyof RuleForm, value: string) => {
  // 过滤空格并确保ruleForm存在
  taskName.value = value.replace(/\s+/g, "");
};

const search = async () => {
  const params = {
    taskName: taskName.value,
    taskType: taskType.value,
    status: status.value,
    currentPage: currentPage.value,
    pageSize: pageSize.value,
  };
  const { data } = await getTaskList(params);
  if (data.records.length > 0) {
    data.records.map((item) => {
      item.status = item.status + "";
    });
    tableData.value = data.records;
    total.value = data.total;
  } else {
    tableData.value = [];
    total.value = 0;
  }
};

const debouncedSearch = useDebounceFn(search, 500);

const resetForm = () => {
  taskName.value = "";
  taskType.value = "";
  status.value = "";
  currentPage.value = 1;
  search();
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  search();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  search();
};

const text = ref("取消");
const updateTask = async (row, status) => {
  if (status === 3) {
    text.value = "终止";
  } else {
    text.value = "取消";
  }
  try {
    await ElMessageBox.confirm(
      `确定${text.value}任务【${row.taskName}】吗？`,
      text.value + "确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              const params = {
                id: row.id,
                status: status,
              };
              await editTaskStatus(params);
              done();
            } catch (error) {
              instance.confirmButtonLoading = false;
            }
          } else {
            done();
          }
        },
      }
    );
    ElMessage.success(text.value + "成功");
    search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`${text.value}失败: ${error.message || "未知错误"}`);
      console.error(text.value + "任务失败:", error);
    }
  }
};

const detailItem = (row) => {
  router.push({
    name: "TaskDetail",
    query: {
      id: row.id,
    },
  });
};

onMounted(() => {
  search();
});
</script>

<template>
  <div class="p-2">
    <div class="search">
      <ElRow>
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="searchCol">
          <span class="marginRight">任务名称：</span>
          <ElInput
            v-model="taskName"
            style="width: 180px"
            placeholder="请输入任务名称"
            clearable
          />
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="searchCol">
          <span class="marginRight">任务类型：</span>
          <ElSelect
            v-model="taskType"
            style="width: 180px"
            placeholder="请选择任务类型"
            @change="search()"
          >
            <ElOption
              v-for="item in taskOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="searchCol">
          <span class="marginRight">任务状态：</span>
          <ElSelect
            v-model="status"
            style="width: 180px"
            placeholder="请选择任务状态"
            @change="search()"
          >
            <ElOption
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="searchCol">
          <ElButton
            type="primary"
            style="margin-left: 30px"
            @click="debouncedSearch"
            >查询</ElButton
          >
          <ElButton @click="resetForm()">重置</ElButton>
        </ElCol>
      </ElRow>
    </div>
    <div class="tablePage">
      <div style="padding: 0 24px 0 16px">
        <ElTable :data="tableData" stripe style="width: 100%" row-key="id">
          <ElTable.TableColumn
            prop="taskName"
            label="任务名称"
            align="center"
          />
          <ElTable.TableColumn
            prop="taskType"
            label="任务类型"
            align="center"
          />
          <ElTable.TableColumn prop="airlineName" label="航线" align="center" />
          <ElTable.TableColumn
            prop="importantLevel"
            label="重要程度"
            align="center"
          />
          <ElTable.TableColumn prop="status" label="任务状态" align="center" />
          <ElTable.TableColumn
            prop="startTime"
            label="执行开始时间"
            align="center"
          />
          <ElTable.TableColumn
            prop="endTime"
            label="执行结束时间"
            align="center"
          />
          <ElTable.TableColumn prop="errCount" label="异常" align="center">
            <template #default="scope">
              <span v-if="scope.row.errCount > 0" style="color: red">{{
                scope.row.errCount
              }}</span>
              <span v-else>{{ scope.row.errCount }}</span>
            </template>
          </ElTable.TableColumn>
          <ElTable.TableColumn fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                v-if="scope.row.status === 1"
                @click="updateTask(scope.row, 4)"
              >
                取消任务
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                v-if="scope.row.status === 2"
                @click="updateTask(scope.row, 3)"
              >
                终止任务
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click="detailItem(scope.row)"
                >详情</el-button
              >
            </template>
          </ElTable.TableColumn>
        </ElTable>
      </div>
      <div class="pagination">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 80, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<style lang="css" scoped>
.search {
  padding: 16px 24px 20px 16px;
  font-size: 14px;
  background: #fff;
}

.tablePage {
  height: calc(100vh - 182px);
  background: #fff;
}

.el-table--fit {
  height: calc(100vh - 260px);
}

:deep(.el-table--fit .el-table__inner-wrapper:before) {
  width: 0 !important;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  padding: 20px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
}

.el-col {
  margin-bottom: 10px;
}

.marginRight {
  margin-right: 10px;
}
</style>
